package vip.ola.pay.batchpay.mengcidf;

import com.alibaba.fastjson.JSONObject;
import org.apache.commons.lang3.StringUtils;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.springframework.stereotype.Service;
import vip.ola.core.common.constant.PayConstant;
import vip.ola.core.common.util.DateUtil;
import vip.ola.core.common.util.MyLog;
import vip.ola.core.common.util.PayDigestUtil;
import vip.ola.core.common.util.PayUtil;
import vip.ola.core.entity.AgentpayPassageAccount;
import vip.ola.core.entity.TransOrder;
import vip.ola.pay.channel.BaseTrans;

import java.io.IOException;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.*;

import static vip.ola.core.common.constant.PayEnum.ERR_0121;

/**
 * @author: dingzhiwei
 * @date: 17/12/25
 * @description:
 */
@Service
public class MengcidfTransService extends BaseTrans {

    private static final MyLog _log = MyLog.getLog(MengcidfTransService.class);

    @Override
    public String getChannelName() {
        return PayConstant.CHANNEL_NAME_ALIPAY;
    }

    public JSONObject trans(TransOrder transOrder) {
        JSONObject retObj = buildRetObj();
        try {
            _log.info("代付转账：" + transOrder.getChannelMchId());
            AgentpayPassageAccount payPassageAccount = rpcCommonService.rpcAgentpayPassageAccountService.findById(transOrder.getPassageAccountId());
            if (payPassageAccount == null || StringUtils.isBlank(payPassageAccount.getParam())) {
                return PayUtil.makeRetFail(ERR_0121);
            }
            JSONObject accountParams = JSONObject.parseObject(payPassageAccount.getParam());
            String mchId = payPassageAccount.getPassageMchId();
            String orderId = transOrder.getTransOrderId();
            String payUrl = accountParams.getString("payUrl");
            String privateKey = accountParams.getString("privateKey");
            TreeMap<String, String> obj = new TreeMap<String, String>();
            obj.put("accountName", transOrder.getAccountName().trim());
            obj.put("accountNo", transOrder.getAccountNo().trim());
            obj.put("amount", String.valueOf(transOrder.getAmount()));
            obj.put("mchId", mchId);
            obj.put("accountAttr", String.valueOf(transOrder.getAccountAttr()));
            obj.put("notifyUrl", accountParams.getString("notify_url"));
            obj.put("mchOrderNo", orderId);
            String reqTime = DateUtil.getSeqString();
            obj.put("reqTime", reqTime);
            if(transOrder.getAccountAttr() == 0){
                obj.put("province", transOrder.getProvince());
                obj.put("city", transOrder.getCity());
                obj.put("bankName", transOrder.getBankName());
                obj.put("bankNumber", transOrder.getBankCode());
                obj.put("bankNetName", transOrder.getBankName());
            }else {
                obj.put("province", "北京");
                obj.put("city",  "北京");
                obj.put("bankName",  "北京上地支行");
                obj.put("bankNumber",  "11473707055");
                obj.put("bankNetName",  "11473707055");
            }
            if ("支付宝".equals(transOrder.getBankName())){
                obj.put("bankName", transOrder.getBankName());
            }
            obj.put("remark", "代付");
            String sign = PayDigestUtil.getSign(obj, privateKey);
            obj.put("sign", sign);
            _log.info("MengcidfTransService代付下单请求url={}，param={},json->{}",payUrl,obj,JSONObject.toJSONString(obj));
            NameValuePair pair = new BasicNameValuePair("mchId", mchId);
            NameValuePair pair2 = new BasicNameValuePair("accountName", transOrder.getAccountName().trim());
            NameValuePair pair3 = new BasicNameValuePair("accountNo", transOrder.getAccountNo().trim());
            NameValuePair pair4 = new BasicNameValuePair("amount", String.valueOf(transOrder.getAmount()));
            NameValuePair pair5 = new BasicNameValuePair("bankName", obj.get("bankName"));
            NameValuePair pair6 = new BasicNameValuePair("remark", "代付");
            NameValuePair pair7 = new BasicNameValuePair("reqTime", reqTime);
            NameValuePair pair8 = new BasicNameValuePair("province", obj.get("province"));
            NameValuePair pair9 = new BasicNameValuePair("notifyUrl", accountParams.getString("notify_url"));
            NameValuePair pair10 = new BasicNameValuePair("mchOrderNo", orderId);
            NameValuePair pair11 = new BasicNameValuePair("city", obj.get("city"));
            NameValuePair pair12 = new BasicNameValuePair("bankNumber", obj.get("bankNumber"));
            NameValuePair pair13 = new BasicNameValuePair("sign", sign);
            NameValuePair pair14 = new BasicNameValuePair("bankNetName", obj.get("bankNetName"));
            NameValuePair pair15 = new BasicNameValuePair("accountAttr", String.valueOf(transOrder.getAccountAttr()));
            List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(16);
            nameValuePairs.add(pair);
            nameValuePairs.add(pair2);
            nameValuePairs.add(pair3);
            nameValuePairs.add(pair4);
            nameValuePairs.add(pair5);
            nameValuePairs.add(pair6);
            nameValuePairs.add(pair7);
            nameValuePairs.add(pair8);
            nameValuePairs.add(pair9);
            nameValuePairs.add(pair10);
            nameValuePairs.add(pair11);
            nameValuePairs.add(pair12);
            nameValuePairs.add(pair13);
            nameValuePairs.add(pair14);
            nameValuePairs.add(pair15);
            String respData = postWithParamsForString(payUrl, nameValuePairs);
            _log.info("下单结束respData->{}",respData);
            if (StringUtils.isNotBlank(respData)){
                JSONObject jsonObject = JSONObject.parseObject(respData);
                retObj.put("transOrderId", transOrder.getTransOrderId());
                if (jsonObject != null){
                    String code = jsonObject.getString("retCode");
                    if ("SUCCESS".equals(code) && "SUCCESS".equals(jsonObject.getString("resCode"))){
                        retObj.put("status",1);
                    }else {
                        retObj.put("status",3);
                        retObj.put("channelErrCode", code);
                        retObj.put("channelErrMsg", jsonObject.getString("retMsg"));
                    }
                }else {
                    retObj.put("status",3);
                    retObj.put("channelErrCode","E0001");
                    retObj.put("channelErrMsg","渠道返回异常，渠道返回为空");
                }
            }else {
                retObj.put("status",3);
                retObj.put("channelErrCode","E0008");
                retObj.put("channelErrMsg","下单异常，渠道返回为空");
            }
        } catch (Exception e) {
            e.printStackTrace();
            retObj.put("status",3);
            retObj.put("channelErrCode","E0009");
            retObj.put("channelErrMsg", e.getMessage());
        }
        return  retObj;
    }


    public static String postWithParamsForString(String url, List<NameValuePair> params){
        HttpClient client = HttpClients.createDefault();
        HttpPost httpPost =   new HttpPost(url);
        String s = "";
        try {
            httpPost.setEntity(new UrlEncodedFormEntity(params,"UTF-8"));
            httpPost.setHeader("Content-type", "application/x-www-form-urlencoded");
            HttpResponse response = client.execute(httpPost);
            int statusCode = response.getStatusLine().getStatusCode();
            if(statusCode==200){
                HttpEntity entity = response.getEntity();
                s = EntityUtils.toString(entity);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return s;
    }



    public JSONObject query(TransOrder transOrder) {
        JSONObject retObj = buildRetObj();
        retObj.put("transOrderId", transOrder.getTransOrderId());
        try {
            AgentpayPassageAccount payPassageAccount = rpcCommonService.rpcAgentpayPassageAccountService.findById(transOrder.getPassageAccountId());
            if (payPassageAccount == null || StringUtils.isBlank(payPassageAccount.getParam())) {
                return PayUtil.makeRetFail(ERR_0121);
            }
            JSONObject accountParams = JSONObject.parseObject(payPassageAccount.getParam());
            String mchId = payPassageAccount.getPassageMchId();
            String orderId = transOrder.getTransOrderId();
            String queryUrl = accountParams.getString("queryUrl");
            String privateKey = accountParams.getString("privateKey");
            Map<String,Object> maps = new HashMap<>();
            maps.put("mchId",mchId);
            maps.put("mchOrderNo",orderId);
            String reqTime = DateUtil.getSeqString();
            maps.put("reqTime", reqTime);
            maps.put("executeNotify", "false");
            String querySign = PayDigestUtil.getSign(maps, privateKey);  //签名
            maps.put("sign", querySign);
            _log.info("MengcidfTransService订单查询请求={}",maps);
            NameValuePair pair = new BasicNameValuePair("mchId", mchId);
            NameValuePair pair3 = new BasicNameValuePair("mchOrderNo", orderId);
            NameValuePair pair4 = new BasicNameValuePair("sign", querySign);
            NameValuePair pair10 = new BasicNameValuePair("executeNotify", "false");
            NameValuePair pair11 = new BasicNameValuePair("reqTime", reqTime);
            List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(16);
            nameValuePairs.add(pair);
            nameValuePairs.add(pair3);
            nameValuePairs.add(pair4);
            nameValuePairs.add(pair10);
            nameValuePairs.add(pair11);
            String respDetail = postWithParamsForString(queryUrl,nameValuePairs);
            _log.info("MengcidfTransService订单查询结果={}",respDetail);
            if (StringUtils.isNotEmpty(respDetail)){
                JSONObject jsonObject = JSONObject.parseObject(respDetail);
                if (jsonObject != null){
                    String code = jsonObject.getString("retCode");
                    if ("SUCCESS".equals(code)){
                        String queryStatus = jsonObject.getString("status");
                        if ("2".equals(queryStatus)){
                            retObj.put("status", 2);
                            retObj.put("channelOrderNo", jsonObject.getString("agentpayOrderId"));
                        }else if ("1".equals(queryStatus) || "0".equals(queryStatus)){
                            retObj.put("status", 1);
                            retObj.put("channelOrderNo", jsonObject.getString("agentpayOrderId"));
                        }else if ("3".equals(queryStatus) ){
                            retObj.put("status", 3);
                            retObj.put("channelOrderNo", jsonObject.getString("agentpayOrderId"));
                            retObj.put("channelErrMsg", jsonObject.getString("transMsg"));
                        }else {
                            retObj.put("status", 1);
                            retObj.put("channelOrderNo", jsonObject.getString("agentpayOrderId"));
                        }
                    }else {
                            retObj.put("status", 1);
                            retObj.put("channelErrCode", code);
                            retObj.put("channelOrderNo", jsonObject.getString("agentpayOrderId"));
                        }
                    }else {
                        retObj.put("status", 1);
                        retObj.put("channelErrCode", jsonObject.getString("retMsg"));
                    }
            }else {
                retObj.put("status", 1);
            }
        } catch (Exception e) {
            retObj.put("status", 1);
        }
        return  retObj;
    }



    @Override
    public JSONObject balance(String payParam) {
        try {
            JSONObject accountParams = JSONObject.parseObject(payParam);
            String mchId = "20000004";
            String privateKey = accountParams.getString("privateKey");
            String balanceUrl = accountParams.getString("balanceUrl");
            TreeMap<String, String> obj = new TreeMap<String, String>();
            SimpleDateFormat fm = new SimpleDateFormat("yyyyMMddHHmmss");
            String reqTime =fm.format(new Date());
            obj.put("reqTime", reqTime);
            obj.put("mchId",mchId);
            // 生成签名
            String querySign = PayDigestUtil.getSign(obj, privateKey);  //签名
            obj.put("sign", querySign);
            _log.info("MengcidfTransService余额查询请求={}",obj);
            NameValuePair pair = new BasicNameValuePair("mchId", mchId);
            NameValuePair pair4 = new BasicNameValuePair("sign", querySign);
            NameValuePair pair11 = new BasicNameValuePair("reqTime", reqTime);
            List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(16);
            nameValuePairs.add(pair);
            nameValuePairs.add(pair4);
            nameValuePairs.add(pair11);
            String respData = postWithParamsForString(balanceUrl,nameValuePairs);
            _log.info("余额查询结束respData->{}",respData);
            if (StringUtils.isNotEmpty(respData)){
                JSONObject jsonObject = JSONObject.parseObject(respData);
                if (jsonObject != null){
                    String code = jsonObject.getString("retCode");
                    if ("SUCCESS".equals(code)  ){
                        Integer totalAmt = jsonObject.getInteger("availableAgentpayBalance");
                        BigDecimal amount = new BigDecimal(totalAmt).divide(new BigDecimal(100)).setScale(2);
                        JSONObject result = new JSONObject();
                        result.put("retCode","SUCCESS");
                        result.put("cashBalance",amount);
                        return result;
                    }
                }
            }
        }catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }



}
